email module是用來分析及產生MIME Text的內容,但實際要送出email需要靠smtplib


In [25]:
title = u'Title'
recipients = [u'banyhung@patentcloud.com']
sender = u'noreply@patentcloud.com'
subject = u'Test subject'
body = u'你好'
server = '10.60.94.110'

In [26]:
import smtplib
from email.mime.text import MIMEText   # 產生 MIME Text
from email.utils import COMMASPACE, formatdate

# 直接由字串產生 MIME Text
msg = MIMEText(body, _charset='utf-8')

# 如果要從檔案中讀取
# with open(textfile, 'rb') as fp:
#     msg = MIMEText(fp.read())

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg['Date'] = formatdate(localtime=True)

s = smtplib.SMTP(server)
s.sendmail(sender, recipients, msg.as_string())
s.quit()


Out[26]:
(221, '2.0.0 nhantispam.scienbizip.com closing connection')

In [27]:
print msg.as_string()


Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Subject: Test subject
From: noreply@patentcloud.com
To: banyhung@patentcloud.com
Date: Thu, 03 Mar 2016 09:56:26 +0800

5L2g5aW9

利用 Parser 讀取MIME header


In [19]:
from email.parser import Parser
headers = Parser().parsestr(msg.as_string())
print headers['to']
print headers['from']
print headers['subject']
print headers['Content-Transfer-Encoding']


banyhung@patentcloud.com
noreply@patentcloud.com
Test subject
base64

在email中附檔


In [32]:
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os import listdir

In [42]:
msg = MIMEMultipart()

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(body, _charset='utf-8'))

for filename in [fn for fn in listdir('.') if fn.endswith('ipynb')]:
    with open(filename, "rb") as fp:
        msg.attach(MIMEApplication(fp.read(),
                                   Content_Disposition='attachment; filename="%s"' % filename,
                                   Name=filename ))

s = smtplib.SMTP(server)
s.sendmail(sender, recipients, msg.as_string())
s.close()

In [ ]: